package com.cbgolf.oa.fragment;

import static com.cbgolf.oa.util.AnimaUtil.stopLoading;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.PermissionHistoryAdapter;
import com.cbgolf.oa.entity.NetResponse;
import com.cbgolf.oa.entity.PermissionsBean;
import com.cbgolf.oa.inteface.INetCallBack;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lq on 2017/9/1.
 */

public class PermissionHistoryFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    public final static String TAG = "F_PermissionHistory";

    //views
    private View view;
    private SwipeRefreshLayout refreshLayout;
    private ListView listView;
    private TextView loadingTv;
    private View errorView;
    private TextView errorTv;
    private TextView reLoadTv;


    //var
    private String status = "";

    private boolean isLoading;

    private int pageSize = 15;
    private int page = 0;
    private final int GET_DATA = 1;
    private final int REFRESH = 2;
    private int getDataType = GET_DATA;


    private List<PermissionsBean> listData = new ArrayList<>();
    private PermissionHistoryAdapter adapter;
    private Handler handler = new Handler();

    public static PermissionHistoryFragment newInstance(String type) {
        PermissionHistoryFragment f_permissionHistory = new PermissionHistoryFragment();
        Bundle b = new Bundle();
        b.putString(TAG, type);
        f_permissionHistory.setArguments(b);
        return f_permissionHistory;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != getArguments()) {
            status = getArguments().getString(TAG);
        }
        view = getActivity().getLayoutInflater().inflate(R.layout.f_permission_history, null);
        init();
        AutoUtil.auto(view);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (null == view) {
            view = inflater.inflate(R.layout.f_permission_history, null);
            init();
            AutoUtil.auto(view);
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void init() {
        findViews();
        setViews();
        setListener();


    }

    private void setListener() {
        refreshLayout.setOnRefreshListener(this);
        reLoadTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (listView.getAdapter() != null && listView.getLastVisiblePosition() == (listView.getAdapter().getCount() - 1)
                        && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (!isLoading) {
                        page++;
                        loadMore();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }


    private void findViews() {
        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.f_permission_swiperRefreshlayout);
        listView = (ListView) view.findViewById(R.id.f_permission_listview);
        errorView = view.findViewById(R.id.g_error_ll);
        errorTv = (TextView) view.findViewById(R.id.g_error_tv);
        reLoadTv = (TextView) view.findViewById(R.id.g_error_reload_tv);
        loadingTv = (TextView) view.findViewById(R.id.g_error_loading_tv);

    }

    private void setViews() {
        adapter = new PermissionHistoryAdapter(getActivity());
        listView.setAdapter(adapter);
        // 设置下拉圆圈上的颜色，蓝色、绿色、橙色、红色
        refreshLayout.setColorSchemeResources(R.color.bg_blue, R.color.text_gray,
                R.color.white, R.color.bg_blue);
//        refreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
//                android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        refreshLayout.setDistanceToTriggerSync(300);// 设置手指在屏幕下拉多少距离会触发下拉刷新
        refreshLayout.setSize(SwipeRefreshLayout.LARGE);
        refreshLayout.setProgressBackgroundColorSchemeColor(ContextCompat.getColor(getActivity(), R.color.white));
//        refreshLayout.setPageCount(pageSize);

    }

    private void getData() {
        isLoading = true;
        if (!Util.isNetWorkConnected()) {
            showError(NONET);
            return;
        }
        String url = WebAPI.permission_history_get;
        Map<String, String> map = new HashMap<>();
        map.put("auditStatus", status);
        map.put("pageSize", pageSize + "");
        map.put("currentPage", "0");
//        fe999ef8-8aef-4960-9366-294550234329
        map.put("token", UserData.getUser() == null ? "" : UserData.getUser().getToken());
        showLoading();
        Web.getOK(url, map, new NetCallBack(new INetCallBack() {
            @Override
            public void onResponse(NetResponse response) {
                if (200 != response.statusCode) {
                    showError(NETERROR);
                    return;
                }
                if (Util.isNull(response.result)) {
                    showError(NODATA);
                    return;
                }
                List<PermissionsBean> list = null;
                try {
                    JSONObject json = JSON.parseObject(response.result);
                    list = JSON.parseArray(json.getString("content"), PermissionsBean.class);
                } catch (Exception e) {
                    showError(NETERROR);
                    return;
                }
                if (null != list && list.size() > 0) {
                    showData();
                    listData.clear();
                    listData.addAll(list);
                    adapter.setData(listData);
                    adapter.upDataUI();
                } else {
                    showError(NODATA);
                }
            }

        }));
    }

    private void showLoading() {
        if (!refreshLayout.isRefreshing())
            AnimaUtil.showLoading(getActivity(), loadingTv);

    }

    private void loadMore() {
        isLoading = true;
        if (!Util.isNetWorkConnected()) {
            showError(LOADMORE);
            return;
        }
        String url = WebAPI.permission_history_get;
        Map<String, String> map = new HashMap<>();
        map.put("auditStatus", status);
        map.put("pageSize", pageSize + "");
        map.put("currentPage", page + "");
        String token = "";
        if (null != UserData.getUser()) {
            token = UserData.getUser().getToken();
        }
        map.put("token", token);
        Web.getOK(url, map, new NetCallBack(new INetCallBack() {
            @Override
            public void onResponse(NetResponse response) {
                if (200 != response.statusCode) {
                    showError(LOADMORE);
                    return;
                }
                if (Util.isNull(response.result)) {
                    showError(LOADMORE);
                    return;
                }
                List<PermissionsBean> list = null;
                try {
                    JSONObject json = JSON.parseObject(response.result);
                    list = JSON.parseArray(json.getString("content"), PermissionsBean.class);
                } catch (Exception e) {
                    showError(LOADMORE);
                    return;
                }
                if (null != list && list.size() > 0) {
                    showData();
                    listData.addAll(list);
                    adapter.upDataUI();
                } else {
                    showError(LOADMORE);
                }
            }

        }));
    }

    private void showData() {
        stopLoading();
        if (null != refreshLayout) {
            refreshLayout.setRefreshing(false);
        }
        isLoading = false;
        refreshLayout.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
    }

    private final int NONET = 1;
    private final int NETERROR = 2;
    private final int NODATA = 3;
    private final int LOADMORE = 4;


    private void showError(int type) {
        stopLoading();
        if (null != refreshLayout) {
            refreshLayout.setRefreshing(false);
        }
        isLoading = false;
        if (type == LOADMORE && page > 0) {
            page--;
        }
        if (listData.size() > 0) {
            return;
        }
        refreshLayout.setVisibility(View.GONE);
        errorView.setVisibility(View.VISIBLE);
        reLoadTv.setVisibility(View.VISIBLE);
        switch (type) {
            case NONET:
                errorTv.setText(getResources().getString(R.string.no_net));
                break;
            case NETERROR:
                errorTv.setText(getResources().getString(R.string.net_error));
                break;
            case NODATA:
                errorTv.setText(getResources().getString(R.string.no_data));
                break;
        }


    }

    @Override
    public void onRefresh() {
        if (!isLoading) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getData();

                }
            }, 200);
        } else {
            if (null != refreshLayout) {
                refreshLayout.setRefreshing(false);
            }
        }
    }
}
